package com.teacold.customdemo.chapter_ten;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class SurfaceViewGesturePath extends SurfaceView {
    private Paint mPaint;
    private Path mPath;

    public SurfaceViewGesturePath(Context context) {
        this(context, null);
    }

    public SurfaceViewGesturePath(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SurfaceViewGesturePath(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
//        setWillNotDraw(false);
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(5);
        mPaint.setColor(Color.RED);
        mPath = new Path();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x= (int) event.getX();
        int y= (int) event.getY();
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            mPath.moveTo(x,y);
            return true;
        }else if(event.getAction()==MotionEvent.ACTION_MOVE){
            mPath.lineTo(x,y);
        }
        drawCancas();
        return super.onTouchEvent(event);
    }

    private void drawCancas() {
        SurfaceHolder surfaceHolder=getHolder();
        Canvas canvas=surfaceHolder.lockCanvas();
        canvas.drawPath(mPath,mPaint);
        surfaceHolder.unlockCanvasAndPost(canvas);
    }


}
